<template>
  <div class="views-changdiyuyue-web-add">
    <div>
      <e-container>
        <el-card class="box-card">
          <template #header>
            <div class="clearfix">
              <span class="title"> 添加场地预约 </span>
            </div>
          </template>

          <el-form :model="form" ref="formModel" :label-width="labelWidth" status-icon validate-on-rule-change>
            <el-form-item v-if="isRead" label="场地编号 " prop="changdibianhao"> {{ form.changdibianhao }} </el-form-item>

            <el-form-item v-if="isRead" label="场地名称 " prop="changdimingcheng"> {{ form.changdimingcheng }} </el-form-item>

            <el-form-item v-if="isRead" label="场地价格 " prop="changdijiage" :rules="[{validator:rule.checkNumber, message:'输入一个有效数字'}]">
              {{form.changdijiage}}
            </el-form-item>

            <el-form-item label="预约编号 " prop="yuyuebianhao" :rules="[{required:true, message:'请填写预约编号'}]">
              <el-input type="text" placeholder="输入预约编号" readonly style="width: 450px" v-model="form.yuyuebianhao" />
            </el-form-item>

            <el-form-item label="预约时间 " prop="yuyueshijian" :rules="[{required:true, message:'请填写预约时间'}]">
              <el-date-picker v-model="form.yuyueshijian" type="date" value-format="YYYY-MM-DD" placeholder="选择日期"
                              :disabled-date="disabledDate"
              > </el-date-picker>
            </el-form-item>


            <el-form-item label="预约时段 " prop="yuyueshiduan" required :rules="[{required:true, message:'请填写预约时段'}]">
              <el-button-group>
                <el-button
                    v-for="(option, index) in filteredTimeOptions"
                    :key="index"
                    :type="form.yuyueshiduan === option.value ? 'primary' : ''"
                    @click="selectTime(option.value)"
                    :disabled="!form.yuyueshijian"
                >
                  {{ option.label }} ({{ bookedTimes[option.value] || 0 }}/{{ route.query.meishiduankeyuyueshu }})
                </el-button>
              </el-button-group>
            </el-form-item>


            <el-form-item label="备注 " prop="beizhu"> <el-input type="textarea" v-model="form.beizhu"></el-input> </el-form-item>

            <el-form-item label="预约人 " prop="yuyueren"> <el-input v-model="form.yuyueren" readonly style="width: 250px"></el-input> </el-form-item>

            <el-form-item v-if="btnText">
              <el-button type="primary" @click="submit">{{ btnText }}</el-button>
            </el-form-item>
          </el-form></el-card
        >
      </e-container>
    </div>
  </div>
</template>

<script setup>
import http from "@/utils/ajax/http";
import DB from "@/utils/db";
import rule from "@/utils/rule";
import router from "@/router";

import { ref, reactive, computed, watch, onMounted } from "vue";
import { useRoute } from "vue-router";
import { session } from "@/utils/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import { useChangdiyuyueCreateForm, canChangdiyuyueInsert } from "@/module";
// import {request} from "axios";

const route = useRoute();
const props = defineProps({
  id: [String, Number],
  btnText: {
    type: String,
    default: "保存",
  },
  isRead: {
    type: Boolean,
    default: true,
  },
  isHouxu: {
    type: Boolean,
    default: true,
  },
  labelWidth: {
    type: String,
    default: "140px",
  },

  // meishiduankeyuyueshu: {  // 新增可预约数prop
  //   type: Number,
  //   default: 0
  // }
});
const { form, readMap } = useChangdiyuyueCreateForm(props.id);
const emit = defineEmits(["success"]);
const formModel = ref();
const loading = ref(false);


// 新添加的预约时段选项数据
const timeOptions = [
  { label: "08:00-10:00", value: "08:00-10:00" },
  { label: "10:00-12:00", value: "10:00-12:00" },
  { label: "12:00-14:00", value: "12:00-14:00" },
  { label: "14:00-16:00", value: "14:00-16:00" },
  { label: "16:00-18:00", value: "16:00-18:00" },
  { label: "18:00-20:00", value: "18:00-20:00" },
  { label: "20:00-22:00", value: "20:00-22:00" }
];


// 已预约时段列表

const bookedTimes = ref({});
//const meishiduankeyuyueshu= route.query.meishiduankeyuyueshu

// 监听预约日期变化
watch(() => form.yuyueshijian, async (newDate) => {
  if (newDate && props.id) {
    try {
      // 获取该日期所有预约记录
      const allRecords = await DB.name("changdiyuyue")
          .where("changdiid", props.id)
          .where("yuyuezhuangtai", "in", ["待支付", "已预约"])
          .where("yuyueshijian", newDate)
          .select();

      // 在客户端进行分组统计
      const counts = {};
      allRecords.forEach(record => {
        counts[record.yuyueshiduan] = (counts[record.yuyueshiduan] || 0) + 1;
      });
      bookedTimes.value = counts;
    } catch (error) {
      console.error("查询预约记录失败:", error);
      bookedTimes.value = {};
    }
  } else {
    bookedTimes.value = {};
  }
}, { immediate: true });

// 过滤后的时段选项
const filteredTimeOptions = computed(() => {
  if (!form.yuyueshijian) return [];

  const selectedDate = new Date(form.yuyueshijian);
  const today = new Date();
  const isToday = selectedDate.toDateString() === today.toDateString();

  return timeOptions.filter(option => {
    // 过滤已约满时段

    const bookedCount = bookedTimes.value[option.value] || 0;
    if (bookedCount >= route.query.meishiduankeyuyueshu) return false;

    // 处理今天的时间过滤
    if (isToday) {
      const [startTimeStr] = option.value.split('-');
      const [startHour, startMinute] = startTimeStr.split(':').map(Number);
      const now = new Date();
      const optionTime = new Date();
      optionTime.setHours(startHour, startMinute, 0, 0);

      return now < optionTime;
    }

    return true;
  });
});


// 处理选择时间的方法
const selectTime = (value) => {
  form.yuyueshiduan = value;
};






// 计算今天的日期（基于本地时间）
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() ); // 今天
tomorrow.setHours(0, 0, 0, 0); // 设置为今天的 00:00:00

// 禁用今天及之前的日期
const disabledDate = (date) => {
  return date < tomorrow;
};



var submit = () => {
  return new Promise((resolve, reject) => {
    formModel.value
        .validate()
        .then((res) => {
          if (loading.value) return;
          loading.value = true;
          canChangdiyuyueInsert(form).then(
              (res) => {
                loading.value = false;
                if (res.code == 0) {
                  emit("success", res.data);
                  if (props.isHouxu) {
                    ElMessage.success("添加成功");


                    router.replace("/admin/changdiyuyue/yuyueren");
                  }
                } else {
                  ElMessageBox.alert(res.msg);
                }
                resolve(res);
              },
              (err) => {
                loading.value = false;
                ElMessageBox.alert(err.message);
                reject(err);
              }
          );
        })
        .catch((err) => {
          reject(err);
        });
  });
};
</script>

<style scoped lang="scss">
.views-changdiyuyue-web-add {
}
</style>
